package vip.xiaonuo.biz.modular.detect.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.modular.detect.service.utils.DetectImageUtil;
import vip.xiaonuo.biz.modular.detect.service.utils.SendEmailUtil;
import vip.xiaonuo.biz.modular.detectrecord.entity.BizDetectRecord;
import vip.xiaonuo.biz.modular.detectrecord.mapper.BizDetectRecordMapper;
import vip.xiaonuo.column.modular.column.entity.BizColumn;
import vip.xiaonuo.column.modular.column.mapper.BizColumnMapper;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.timer.CommonTimerTaskRunner;
import vip.xiaonuo.dev.modular.config.entity.DevConfig;
import vip.xiaonuo.dev.modular.config.mapper.DevConfigMapper;
import vip.xiaonuo.henhouse.modular.henhouse.entity.BizHenhouse;
import vip.xiaonuo.henhouse.modular.henhouse.mapper.BizHenhouseMapper;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;

/**
 * 定期扫描文件夹并检测其中的图片文件
 *
 * @author
 * @date 2024/3/1、15:49
 */
@Slf4j
@Component
public class DetectTask implements CommonTimerTaskRunner {

    @Resource
    private DevConfigMapper devConfigMapper;

    @Resource
    private DetectImageUtil detectImageUtil;

    @Resource
    private BizHenhouseMapper henhouseMapper;

    @Resource
    private BizColumnMapper columnMapper;

    @Resource
    private BizDetectRecordMapper detectRecordMapper;

    //配置项KEY
    private final String CONFIG_KEY = "biz_detect_path";
    //可处理的文件扩展名
    private static final String[] IMAGE_EXTENSIONS = {".jpg", ".png"};

    @Override
    public void action() {
        File folder = new File(getPath());
        traverseFolder(folder);
        detectImageUtil.closeProcess();
    }

    //遍历文件夹
    private void traverseFolder(File folder) {
        //如果文件夹存在并且确实是文件夹
        if (folder.exists() && folder.isDirectory()) {
            File[] files = folder.listFiles();
            //开始遍历
            if (files != null) {
                for (File file : files) {
                    //如果是文件则校验是否是图片文件
                    if (file.isFile()) {
                        if (isImageFile(file.getName())) {
                            //先将图片文件复制到tmp文件夹中，因为图片检测时无法使用中文路径
                            String tmpPath = "D:\\chicken_images\\henhouse\\tmp\\" + file.getName();
                            Path sourcePath = Paths.get(file.getPath());
                            Path destinationPath = Paths.get(tmpPath);
                            try {
                                // 复制文件
                                Files.copy(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
                                detectImage(tmpPath, file.getPath());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    } else if (file.isDirectory()) {
                        traverseFolder(file);
                    }
                }
            }
            try {
                clearTmp();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private static void clearTmp() throws IOException {
        //清空tmp文件夹
        Path directoryPath = Paths.get("D:\\chicken_images\\henhouse\\tmp");
        // 遍历目录中的文件和子目录
        Files.walk(directoryPath)
                .forEach(path -> {
                    try {
                        // 如果是文件，则删除
                        if (Files.isRegularFile(path)) {
                            Files.delete(path);
                            System.out.println("Deleted file: " + path);
                        }
                        //else if (Files.isDirectory(path) && Files.list(path).count() == 0) {
                        //    // 如果是空目录，则删除
                        //    Files.delete(path);
                        //    System.out.println("Deleted empty directory: " + path);
                        //}
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
    }

    //检测图片
    private void detectImage(String path, String pathStr) {
        String res = detectImageUtil.executeProcess(path);
        if (res.equals("error")) {
            log.info("病鸡监测定时任务出现未知异常！");
            throw new CommonException("病鸡监测定时任务出现未知异常！");
        } else if (res.equals("异常")) {
            handleSickChicken(pathStr);
        }
        createRecord(pathStr,res);
    }

    //创建检测记录
    private void createRecord(String pathStr,String res){
        LambdaQueryWrapper<BizHenhouse> henhouseLambdaQueryWrapper = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<BizColumn> columnLambdaQueryWrapper = new LambdaQueryWrapper<>();

        String[] str = getHenhouseAndColumn(pathStr);
        String henhouseName = str[0];
        String columnName = str[1];

        henhouseLambdaQueryWrapper.eq(BizHenhouse::getName,henhouseName).select(BizHenhouse::getId);
        columnLambdaQueryWrapper.eq(BizColumn::getName,columnName).select(BizColumn::getId,BizColumn::getBarnId);
        BizHenhouse henhouse = henhouseMapper.selectOne(henhouseLambdaQueryWrapper);
        BizColumn bizColumn = columnMapper.selectOne(columnLambdaQueryWrapper);

        BizDetectRecord bizDetectRecord = new BizDetectRecord();
        bizDetectRecord.setHenhouseId(henhouse.getId());
        bizDetectRecord.setBarnId(bizColumn.getBarnId());
        bizDetectRecord.setColumnId(bizColumn.getId());
        bizDetectRecord.setResult(res);
        bizDetectRecord.setCreateTime(new Date());

        detectRecordMapper.insert(bizDetectRecord);
    }

    //path是用来处理图片的真正路径，pathStr是用来找鸡舍名和栏舍名的
    private void handleSickChicken(String pathStr) {
        String[] str = getHenhouseAndColumn(pathStr);
        String henhouseName = str[0];
        String columnName = str[1];
        // 获取目标邮箱
        SaBaseLoginUser saBaseLoginUser = StpLoginUserUtil.getLoginUser();
        String email = saBaseLoginUser.getEmail();

        String subject = "鸡悦乐-预警通知";
        String content = "鸡场的" + henhouseName + "的" + columnName + "出现异常，请及时处理！";

        log.info("向{}发送邮件，主题为：{}，内容为：{}", email, subject, content);
        SendEmailUtil.sendEmail(email, subject, content);
    }

    private String[] getHenhouseAndColumn(String pathStr){
        String henhouseName = "";
        String columnName = "";
        String[] parts = pathStr.split("\\\\");
        if (parts.length >= 4) {
            henhouseName = parts[parts.length - 4];
            columnName = parts[parts.length - 2];
        }
        return new String[] {henhouseName,columnName};
    }

    //根据文件名判断文件是否是图片文件
    private boolean isImageFile(String fileName) {
        for (String ext : IMAGE_EXTENSIONS) {
            if (fileName.endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

    //获取配置的文件路径
    private String getPath() {
        LambdaQueryWrapper<DevConfig> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(DevConfig::getConfigValue).eq(DevConfig::getConfigKey, CONFIG_KEY);
        DevConfig devConfig = devConfigMapper.selectOne(queryWrapper);
        return devConfig.getConfigValue();
    }

}
